import { Api, AxIosInstance } from "../api"
import { resolve } from "upath";
import { rejects } from "assert";
import cookie from "vue-cookies"

const cookieLangKey = "CurrentLanguage"


export default {
    namespaced: true,
    state: () => {
        return {
            rtl: true,
            language: "تىل",
            select_language: "تىل تاللاڭ",
            initialize: "دەسلەپلەشتۈرۈڭ",
            name: "ئىسمى"
        }
    },
    mutations: {
        updateObject(state, { langCode, data }) {
            updateResources(state, data)
        }
    },
    actions: {

    },

    modules: {
        management: {
            namespaced: true,
            state: {
                current: cookie.get(cookieLangKey) || "ug",
                available: null
            },
            mutations: {
                setAvailable(state, data) {
                    state.available = data
                },
                setCurrent(state, langCode){
                    state.current = langCode
                }
            },
            actions: {
                listLanguages(context) {
                    return new Promise((resolve, rejects) => {
                        AxIosInstance.get(Api.languageList()).then(data => {
                            context.commit("setAvailable", data.data)
                            resolve(data.data)
                        }).catch(exception => {
                            rejects(exception)
                        })
                    })
                },

                changeLanguage(context, langCode) {
                    return new Promise((resolve, rejects) => {
                        let expire = new Date()
                        expire.setFullYear(expire.getFullYear() + 1)

                        cookie.set(cookieLangKey, langCode, expire)

                        AxIosInstance.get(Api.languageStrings(langCode)).then(success => {
                            this.commit("lang/updateObject", {
                                langCode,
                                data: success.data
                            })
                            context.commit("setCurrent", langCode)
                            resolve(true)
                        }).catch(error => {
                            console.log(error)
                            rejects(error)
                        })
                    })

                },
                async loadDefault({ dispatch, state }) {
                    return dispatch("changeLanguage", state.current)
                }
            }
        }
    }
}


function updateResources(strings, data) {
    strings.name = data.name
    strings.rtl = data.rtl
    strings.select_language = data.select_language
    strings.initialize = data.initialize
    strings.language = data.language
}